package cn.springcloud.alibaba.gateway.controller;

import cn.springcloud.alibaba.core.base.Result;
import cn.springcloud.alibaba.core.constant.Constant;
import cn.springcloud.alibaba.gateway.vo.VerificationCode;
import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/verification")
public class VerificationCodeController {

	@Autowired
	private Producer producer;
	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	@GetMapping(value = "/code")
	public Result<VerificationCode> code() {
		//生成验证码
		String code = producer.createText();
		//保存验证码信息
		String uuid = UUID.randomUUID().toString().replaceAll("-", "");
		String key = Constant.CAPTCHA_KEY + ":" + uuid;
		stringRedisTemplate.opsForValue().set(key, code, 3, TimeUnit.MINUTES);
		log.info("[key]:{}, [capText]:{}", key, code);
		VerificationCode verificationCode = new VerificationCode();
		verificationCode.setCode(code);
		verificationCode.setUuid(uuid);

		Result<VerificationCode> result = new Result<>();
		result.setData(verificationCode);
		return result;
	}
}
